package com.qingzhuge.manager.security.handler;

import cn.hutool.http.HttpStatus;
import com.google.gson.Gson;
import com.qingzhuge.common.HttpCode;
import com.qingzhuge.dto.response.ResponseBodyDto;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.MediaType;
import org.springframework.security.authentication.*;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * @author zeroxiao
 * @date 2019/9/10 20:42
 * 认证失败事件处理器
 */
@Slf4j
public class LoginFailureEvenHandler implements AuthenticationFailureHandler {

    @Override
    public void onAuthenticationFailure(HttpServletRequest request,
                                        HttpServletResponse response,
                                        AuthenticationException exception) throws IOException {
        String message = HttpCode.LOGIN_FAIL.message();
        if (log.isDebugEnabled()){
            if (exception instanceof UsernameNotFoundException){
                message = "debug:账号不正确";
            }else if(exception instanceof BadCredentialsException){
                message = "debug:密码不正确";
            }else if(exception instanceof AccountStatusException){
                message = "debug:账号状态禁用";
            }else if(exception instanceof AccountExpiredException){
                message = "debug:账号过期";
            }else if(exception instanceof LockedException){
                message = "debug:账号锁定";
            }else if(exception instanceof DisabledException){
                message = "debug:账号末启用";
            }
            log.debug("登录失败:[{}]",message);
        }
        response.setCharacterEncoding("UTF8");
        response.setContentType(MediaType.APPLICATION_JSON_UTF8_VALUE);
        ResponseBodyDto<String> result = new ResponseBodyDto<>();
        result.setCode(HttpCode.LOGIN_FAIL.value());
        result.setMessage(message);
        response.setStatus(HttpStatus.HTTP_OK);
        PrintWriter printWriter = response.getWriter();
        printWriter.append(new Gson().toJson(result));
    }
}